package com.education.api.controller.admin;


import com.education.business.service.system.SystemAdminService;
import com.education.business.task.TaskManager;
import com.education.business.task.TaskParam;
import com.education.business.task.UserLoginSuccessListener;
import com.education.common.base.BaseController;
import com.education.common.constants.Constants;
import com.education.common.model.JwtToken;
import com.education.common.util.RequestUtils;
import com.education.common.util.Result;
import com.education.common.util.ResultCode;
import com.education.model.dto.AdminUserSession;
import com.education.model.request.UserLoginRequest;
import com.jfinal.kit.Kv;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 系统登录
 * @author 余一
 * @date 2021/9/11  16:24
 */
@RestController
@RequestMapping("/system")
@Api(value = "管理员登录登出接口",tags = "系统登录登出接口")
public class LoginController extends BaseController {
    @Autowired
    private SystemAdminService systemAdminService;

    @Autowired
    private JwtToken adminJwtToken;

    @Autowired
    private TaskManager taskManager;

    /**
     * 系统管理员登录接口
     * @return
     */
    @PostMapping("/login")
    public Result<Map> login(@RequestBody @Validated UserLoginRequest userLoginRequest, HttpServletResponse response,
                             HttpServletRequest request){
        String key = userLoginRequest.getKey();
        String imageCode = userLoginRequest.getCode();
        String cacheCode = cacheBean.get(key);
        if (!imageCode.equalsIgnoreCase(cacheCode)) {
            return Result.fail(ResultCode.CODE_ERROR,"验证码输入错误！");
        }
        Result result = systemAdminService.login(userLoginRequest.getUsername(),userLoginRequest.getPassword());
        if (result.isSuccess()) {
            Integer adminUserId = systemAdminService.getAdminUserId();
            //生成JwtToken
            String jwtToken = adminJwtToken.createJwtToken(adminUserId, Constants.SESSION_TIME_OUT_MILLISECONDS);//默认缓存5天
            AdminUserSession adminUserSession = systemAdminService.getAdminUserSession();
            //加载用户角色菜单信息并封装到adminUserSession中
            systemAdminService.loadUserMenuAndPermission(adminUserSession);
            String sessionId = request.getSession().getId();
            adminUserSession.setSessionId(sessionId);
            adminUserSession.setToken(jwtToken);
            Kv userInfo = Kv.create().set("token",jwtToken).set("id",adminUserSession.getAdminId())
                    .set("permissionList",adminUserSession.getPermissionList())
                    .set("menuList",adminUserSession.getMenuTreeList())
                    .set("login_name",adminUserSession.getSystemAdmin().getLoginName());
            HashMap<Object, Object> resultMap = new HashMap<>();
            resultMap.put("userInfo",userInfo);
            //异步更新用户相关信息
            TaskParam taskParam = new TaskParam(UserLoginSuccessListener.class);
            taskParam.put("userSession",adminUserSession);
            taskParam.put("request", RequestUtils.getRequest());
            taskManager.pushTask(taskParam);
            // 更新shiro 用户信息，避免与redis 缓存中用户信息不一致问题
            systemAdminService.updateShiroCacheUserInfo(adminUserSession);
            result.setData(resultMap);
        }
        return result;
    }

    @GetMapping("unAuth")
    public Result unAuth() {
        return Result.success(ResultCode.UN_AUTH_ERROR_CODE, "用户未认证");
    }
}
